CREATE  trigger tfb_cashflow_au on dbo.tfb_cashflow 
after update

as   

   
begin   

  set nocount on
  declare @nyear integer   
  declare @nmonth integer   
  declare @nflowid integer   
  declare @voucherid int , @filid int

  select @voucherid=voucherid,@filid=filid,@nflowid=flowid from inserted

  if (@voucherid>0) 
  begin   
   
    select  @nyear=cast(substring(c.vouyearmonth,1,4) as integer),   
      @nmonth=cast(substring(c.vouyearmonth,5,6) as integer)   
      from tfb_voucher c,inserted   
      where c.voucherid=inserted.voucherid  and c.filid=inserted.filid  
   
    if ((@nyear is not null) and (@nmonth is not null))
    begin   
      delete from tfb_cashflowinit   
        where flowid=@nflowid   
          and nyear=@nyear   
          and nmonth=@nmonth and filid=@filid   
   
      insert into tfb_cashflowinit( flowid,nyear, nmonth,debit, credit,filid)   
      select @nflowid,@nyear,@nmonth,   
        sum(a.debit),sum(a.credit)  ,@filid
      from tfb_cashflow a   
      inner join tfb_voucher c on a.voucherid=c.voucherid   
      where a.flowid=@nflowid and a.voucherid>0   
        and cast(substring(c.vouyearmonth,1,4) as integer)=@nyear   
        and cast(substring(c.vouyearmonth,5,6) as integer)=@nmonth and a.filid=c.filid and a.filid=@filid   
    end   
  end   
end


